﻿using System;
using System.Data;
using System.IO;

namespace SqliteLoader
{
	public class CsvWriter
	{

		public CsvWriter(bool header, bool useQuote, char delimiter)
		{
			Header = header;
			UseQuote = useQuote;
			Delimiter = delimiter;
		}

		public bool Header { get; set; }
		public bool UseQuote { get; set; }
		public char Delimiter { get; set; }

		public void Write(DataTable table, string fileName)
		{
			using (var stream = new FileStream(fileName, FileMode.Create))
			using (var writer = new StreamWriter(stream))
			{
				if (Header)
				{
					var columnNames = new string[table.Columns.Count];
					for (int i = 0; i < table.Columns.Count; i++)
						columnNames[i] = table.Columns[i].ColumnName;
					writer.WriteLine(string.Join(Delimiter.ToString(), columnNames));
				}

				foreach (DataRow row in table.Rows)
				{
					var objectValues = row.ItemArray;
					int notNullCnt = 0;
					for (int i = 0; i < objectValues.Length; i++)
						if (objectValues[i] == DBNull.Value)
							objectValues[i] = null;
						else if (!string.IsNullOrEmpty(Convert.ToString(objectValues[i])))
							notNullCnt++;

					var values = new string[objectValues.Length];
					objectValues.CopyTo(values, 0);

					if (UseQuote)
						for (int i = 0; i < values.Length; i++)
							if (!string.IsNullOrEmpty(values[i]) && values[i].Contains(Delimiter.ToString()))
								values[i] = "\"" + values[i].Replace("\"", "\"\"") + "\"";

					if (notNullCnt > 0)//some values to write
						writer.WriteLine(string.Join(Delimiter.ToString(), values));
					else //no values to write
						writer.WriteLine(); //write empty line
				}
			}
		}
	}
}